package com.adcc.loadsheet.monitor.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.monitor.entity.User;
import com.adcc.loadsheet.monitor.util.Constant;
import com.adcc.loadsheet.monitor.util.SystemConfigFactory;
import com.adcc.loadsheet.monitor.vo.ResultStatus;
import com.adcc.loadsheet.monitor.vo.ResultVO;
import com.google.common.collect.Maps;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 核心控制层
 */
@Controller
public class CoreController {

    @Autowired
    private SystemConfigFactory systemConfigFactory;


    @RequestMapping(value="/", method = RequestMethod.GET)
    public String home() {
        return "login";
    }

    /**
     * 加载起始页
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String loadIndex(HttpSession session) {
        session.setAttribute("roleDisable", systemConfigFactory.getRoleDisable().get("roleDisable"));
        return "index";
    }

    @RequestMapping(value="/turn", method = RequestMethod.GET)
    public String turn(String url) {
        return url;
    }

    @RequestMapping(value="/getServerDateTime", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getServerDateTime(){
        Map<String, String> map = Maps.newHashMapWithExpectedSize(1);
        map.put("serverDateTime", DateTime.now(DateTimeZone.UTC).toString("yyyy-MM-dd HH:mm:ss"));
        return map;
    }

    /**
     * 用户注销
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ResponseBody
    public ResultVO logout(HttpSession session) {
        ResultVO vo = new ResultVO();
        try {
            User user = (User) session.getAttribute("user");
            if(user != null){
                session.removeAttribute("user");
            }
        } catch (Exception ex) {
            Log.error(CoreController.class, "logout() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(Constant.ERROR_LOGOUT);
        }
        return vo;
    }
}
